package lws.com.liwushuo.view.fragment.fenlei;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import lws.com.liwushuo.R;
import lws.com.liwushuo.adapter.fenlei.DanpinListviewAdapter;
import lws.com.liwushuo.adapter.fenlei.DanpinRecyclerviewAdapter;
import lws.com.liwushuo.adapter.fenlei.DanpinRecyclerviewAdapter1;
import lws.com.liwushuo.bean.fenlei.DanpinBean;
import lws.com.liwushuo.server.fenlei.FenleiService;
import lws.com.liwushuo.utils.ScrollListenerRecyclerview;
import lws.com.liwushuo.view.activity.DetailsDanpinActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * OurApp simple {@link Fragment} subclass.
 */
public class DanpinFragment extends Fragment implements Callback<DanpinBean>, AdapterView.OnItemClickListener, DanpinRecyclerviewAdapter1.OnRecyclerViewItemClickListener, ScrollListenerRecyclerview.OnItemScrollChangeListener {

    private View view;
    private FenleiService server;
    private int lastSelectedPosition;
    private int selectedPosition;
    private ListView listView;
    private ScrollListenerRecyclerview recyclerView;
    private DanpinListviewAdapter danpinListviewAdapter;
    private DanpinRecyclerviewAdapter danpinRecyclerviewAdapter;
    private DanpinRecyclerviewAdapter1 danpinRecyclerviewAdapter1;
    private List<List<Object>> subcategoriesBeanList;

    private boolean isFirst = true;
    private int listviewItemHeight;

    private boolean isFirstItemHeight = true;
    private LinearLayoutManager layoutManager;

    //联动相关
    public boolean flag;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_danpin, container, false);
        listView = ((ListView) view.findViewById(R.id.lv_danpin));
        recyclerView = ((ScrollListenerRecyclerview) view.findViewById(R.id.rv_danpin));

        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setOnItemScrollChangeListener(this);
        listView.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        danpinListviewAdapter = new DanpinListviewAdapter(getContext(), new ArrayList<String>(), this);
        danpinRecyclerviewAdapter1 = new DanpinRecyclerviewAdapter1(getContext());
        subcategoriesBeanList = new ArrayList<>();

        danpinRecyclerviewAdapter1.setOnRecyclerViewItemClickListener(this);

        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://api.liwushuo.com").addConverterFactory(GsonConverterFactory.create()).build();
        server = retrofit.create(FenleiService.class);
        server.getDanpinBean().enqueue(this);

    }

    @Override
    public void onResponse(Call<DanpinBean> call, Response<DanpinBean> response) {
        DanpinBean body = response.body();

        for (DanpinBean.DataBean.CategoriesBean categoriesBean : body.getData().getCategories()) {
            danpinListviewAdapter.add(categoriesBean.getName());

            ArrayList<Object> nameString = new ArrayList<>();
            //先添加名字
            if (!isFirst) {
                nameString.add(categoriesBean.getName());
                subcategoriesBeanList.add(nameString);
                //添加布局类型的id
                danpinRecyclerviewAdapter1.getType().add(DanpinRecyclerviewAdapter1.TITLE);
            } else {
                isFirst = false;
            }

            int size = categoriesBean.getSubcategories().size();
            int rowCount = (size + 2) / 3;

            for (int i = 0; i < rowCount; i++) {
                ArrayList<Object> subcategoriesBeen = new ArrayList<>(); //再添加三个图片的那一行的数据

                danpinRecyclerviewAdapter1.getType().add(DanpinRecyclerviewAdapter1.THREE_IMAGES);
                subcategoriesBeen.add(categoriesBean.getSubcategories().get(i * 3));
                if (i * 3 + 1 <= size - 1) {
                    subcategoriesBeen.add(categoriesBean.getSubcategories().get(i * 3 + 1));
                }
                if (i * 3 + 2 <= size - 1) {
                    subcategoriesBeen.add(categoriesBean.getSubcategories().get(i * 3 + 2));
                }
                subcategoriesBeanList.add(subcategoriesBeen);  //再添加三个图片的那一行的数据
            }
        }
        danpinRecyclerviewAdapter1.setSubcategoriesBeanList(subcategoriesBeanList);
        listView.setAdapter(danpinListviewAdapter);
        recyclerView.setAdapter(danpinRecyclerviewAdapter1);

    }

    public int getSelectedPosition() {
        return selectedPosition;
    }

    @Override
    public void onFailure(Call<DanpinBean> call, Throwable t) {

    }


//        int topTo = -(i-1) * listviewItemHeight;
//        int topNow = adapterView.getTop();
//        Log.e("自定义标签", "类DanpinFragment中的方法onItemClick: topTo: "+topTo+"  topNow: "+topNow);
//        ViewCompat.setTranslationY(adapterView,topTo- topNow);
//        listView.smoothScrollToPosition(5);
//        listView.setSelection(5);
//        listView.smoothScrollToPositionFromTop(i,listviewItemHeight);

//        recyclerView.smoothScrollToPosition(getRecyclerviewTypePosition(i));

//        recyclerView.smoothScrollBy();
//        recyclerView.scrollToPosition(getTypePosition(i));

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (lastSelectedPosition == i) {
            return;
        }
        flag = false; //设置此时调用onChange无效
        flag(i, false);
    }

    public void flag(int i, final boolean aFlag) {
        if (isFirstItemHeight) {
            listviewItemHeight = view.getMeasuredHeight();
            isFirstItemHeight = false;
        }
        selectedPosition = i;
        danpinListviewAdapter.notifyDataSetChanged();
        Log.e("自定义标签", "类DanpinFragment中的方法flag: listView绘制完成" + " aFlag: " + aFlag);
//        danpinListviewAdapter.setItemStateChange(lastSelectedPosition,selectedPosition);
        if (!aFlag) {   //说明是listView的Item被点击
            recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { //停止状态
//                        Log.e("自定义标签", "类DanpinFragment中的方法onScrollStateChanged: ");
                        flag = true;
                    } else if (newState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {  //快速滑动状态
//                        flag = false;
                    } else if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { //正在滚动

                    }
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                }
            });
            layoutManager.scrollToPositionWithOffset(getRecyclerviewTypePosition(i), 0);
//            flag = quanjuFlag;
        } else {
            a(i,false);
            flag = true;
        }
        lastSelectedPosition = i;
    }

    public void a(int i, final boolean aFlag){
        if (isFirstItemHeight) {
            listviewItemHeight = view.getMeasuredHeight();
            isFirstItemHeight = false;
        }
        selectedPosition = i;
        danpinListviewAdapter.notifyDataSetChanged();
        lastSelectedPosition = i;
    }

    public int getRecyclerviewTypePosition(int position) {
        int index = 0;
        int titleCount = 0;
        if (position == 0) {
            return 0;
        }
        for (Integer integer : danpinRecyclerviewAdapter1.getType()) {
            if (integer == DanpinRecyclerviewAdapter1.TITLE) {
                titleCount++;
            }
            index++;
            if (titleCount == position) {
                return index - 1;
            }
        }
        return index;
    }

    /**
     * 根据Recyclerview的可见的Item中最上面的Item的position获得Listview应该被选中的的对应项
     *
     * @param position
     * @return
     */
    public int getListviewItemPosition(int position) {
        int titleCount = 0;
        if (position == 0) {
            return 0;
        } else if (position == danpinRecyclerviewAdapter1.getType().size() - 5 && position == danpinRecyclerviewAdapter1.getType().size() - 6) {
            return danpinListviewAdapter.getList().size() - 1;
        }
        for (int i = 0; i <= position; i++) {
            Integer integer = danpinRecyclerviewAdapter1.getType().get(i);
            if (integer == DanpinRecyclerviewAdapter1.TITLE) {
                titleCount++;
            }
            if (i == position) {
                return titleCount;
            }
        }
        return titleCount;
    }

    @Override
    public void onRecyclerViewItemClick(View view, DanpinBean.DataBean.CategoriesBean.SubcategoriesBean subcategoriesBean) {
        Intent intent = new Intent(getContext(), DetailsDanpinActivity.class);
        intent.putExtra("id", subcategoriesBean.getId());
        intent.putExtra("name", subcategoriesBean.getName());
        startActivity(intent);
    }

    /**
     * @param view     第一个可见的子view
     * @param position 第一个可见的子view的position
     */
    @Override
    public void onChange(View view, int position) {
//        Log.e("自定义标签", "类DanpinFragment中的方法onChange: ");
//        if (flag/* && position == getRecyclerviewTypePosition(getSelectedPosition())*/) {
//            Log.e("自定义标签", "类DanpinFragment中的方法onChange: ");
//            int listviewItemPosition = getListviewItemPosition(position);
//            flag(listviewItemPosition, true);
//        }
    }
}
